package kuaidi;

import until.DBUtil;

import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.sql.*;

public class AdminOperatePanel extends JPanel {
    private CardLayout cardLayout;
    private JPanel cardPanel;
    private ImportPanel importPanel;
    private JPanel expressPanel;
    private JTable table;
    private DefaultTableModel model;

    public AdminOperatePanel() {
        setLayout(new BorderLayout());

        JPanel btnPanel = new JPanel();
        JButton importBtn = new JButton("导入包裹");
        JButton viewBtn = new JButton("取走包裹");
        importBtn.setBackground(Color.CYAN);
        viewBtn.setBackground(Color.ORANGE);
        btnPanel.add(importBtn);
        btnPanel.add(viewBtn);
        add(btnPanel, BorderLayout.NORTH);

        cardLayout = new CardLayout();
        cardPanel = new JPanel(cardLayout);
        importPanel = new ImportPanel();
        expressPanel = createExpressPanel();

        cardPanel.add(importPanel, "import");
        cardPanel.add(expressPanel, "express");
        add(cardPanel, BorderLayout.CENTER);

        importBtn.addActionListener(e -> cardLayout.show(cardPanel, "import"));
        viewBtn.addActionListener(e -> {
            refreshTable();
            cardLayout.show(cardPanel, "express");
        });
    }

    private JPanel createExpressPanel() {
        JPanel panel = new JPanel(new BorderLayout());

        // 添加"状态"和"创建时间"列
        model = new DefaultTableModel(new Object[]{
                "ID", "寄件人", "电话", "收件人", "收件电话", "地址", "尺寸", "取件码", "柜子ID", "状态", "创建时间", "操作"
        }, 0);

        table = new JTable(model);
        table.setRowHeight(30);
        table.getColumn("操作").setCellRenderer(new ButtonRenderer());
        table.getColumn("操作").setCellEditor(new ButtonEditor(new JCheckBox()));

        JScrollPane scrollPane = new JScrollPane(table);
        panel.add(scrollPane, BorderLayout.CENTER);

        return panel;
    }

    private void refreshTable() {
        model.setRowCount(0); // 清空旧数据
        try (Connection conn = DBUtil.getConnection()) {
            // 只查询待寄出的包裹
            String sql = "SELECT * FROM send_express WHERE status = '待寄出'";
            try (PreparedStatement ps = conn.prepareStatement(sql);
                 ResultSet rs = ps.executeQuery()) {
                while (rs.next()) {
                    model.addRow(new Object[]{
                            rs.getInt("id"),
                            rs.getString("sender_name"),
                            rs.getString("sender_phone"),
                            rs.getString("recipient_name"),
                            rs.getString("recipient_phone"),
                            rs.getString("recipient_address"),
                            rs.getString("size"),
                            rs.getString("code"),
                            rs.getInt("locker_id"),
                            rs.getString("status"),
                            rs.getTimestamp("create_time"),
                            "取走"
                    });
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库错误：" + e.getMessage());
        }
    }

    // 渲染器
    class ButtonRenderer extends JButton implements TableCellRenderer {
        public ButtonRenderer() {
            setOpaque(true);
        }

        @Override
        public Component getTableCellRendererComponent(JTable table, Object value,
                                                       boolean isSelected, boolean hasFocus,
                                                       int row, int column) {
            setText(value == null ? "取走" : value.toString());
            return this;
        }
    }

    // 编辑器
    class ButtonEditor extends DefaultCellEditor {
        private JButton button;
        private int currentRow;

        public ButtonEditor(JCheckBox checkBox) {
            super(checkBox);
            button = new JButton("取走");
            button.setOpaque(true);
            button.addActionListener(e -> handleRemove(currentRow));
        }

        @Override
        public Component getTableCellEditorComponent(JTable table, Object value,
                                                     boolean isSelected, int row, int column) {
            currentRow = row;
            return button;
        }

        @Override
        public Object getCellEditorValue() {
            return "取走";
        }
    }

    private void handleRemove(int row) {
        int id = (int) model.getValueAt(row, 0);         // send_express.id
        String code = (String) model.getValueAt(row, 7); // 取件码
        int lockerId = (int) model.getValueAt(row, 8);   // locker_id

        try (Connection conn = DBUtil.getConnection()) {
            conn.setAutoCommit(false);

            try {
                // 1. 更新send_express表状态为"已寄出"
                String updateSendSql = "UPDATE send_express SET status = '已寄出'  WHERE id = ?";
                try (PreparedStatement updateSendPs = conn.prepareStatement(updateSendSql)) {
                    updateSendPs.setInt(1, id);
                    updateSendPs.executeUpdate();
                }

                // 2. 更新lockers表状态为"空闲"
                String updateLockerSql = "UPDATE lockers SET status = '空闲' WHERE id = ?";
                try (PreparedStatement updLockerPs = conn.prepareStatement(updateLockerSql)) {
                    updLockerPs.setInt(1, lockerId);
                    updLockerPs.executeUpdate();
                }

                // 3. 更新parcels表状态为"已寄出"，并设置取件时间
                String updateParcelSql = "UPDATE parcels SET status = '已寄出', pickup_time = NOW() WHERE code = ? AND locker_id = ?";
                try (PreparedStatement updParcelPs = conn.prepareStatement(updateParcelSql)) {
                    updParcelPs.setString(1, code);
                    updParcelPs.setInt(2, lockerId);
                    updParcelPs.executeUpdate();
                }

                conn.commit();
                JOptionPane.showMessageDialog(this, "包裹状态已更新为已寄出！");
                refreshTable();

            } catch (SQLException e) {
                conn.rollback();
                throw e;
            }
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "数据库错误：" + e.getMessage());
        }
    }
}